# -*- coding: utf-8 -*-


from odoo import api, fields, models, _
from odoo.exceptions import ValidationError, UserError
from odoo.tools import float_compare, float_is_zero


class AccountAdvancePaymentWizard(models.TransientModel):
    _name = "expense.advance.payment.wizard"
    _description = u"借款付款"

    @api.model
    def _default_partner_id(self):
        context = dict(self._context or {})
        active_ids = context.get('active_ids', [])
        payment = self.env['expense.advance.payment'].browse(active_ids)
        return payment.employee_id.address_home_id
    journal_id = fields.Many2one('account.journal', string='付款方式', required=True,
                                 domain=[('type', 'in', ('bank', 'cash'))])
    company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', readonly=True,
                                 required=True)

    payment_method_id = fields.Many2one('account.payment.method', string='Payment Type', required=True)
    amount = fields.Monetary(string='Payment Amount', required=True)
    currency_id = fields.Many2one('res.currency', string='Currency', required=True,
                                  default=lambda self: self.env.user.company_id.currency_id)
    payment_date = fields.Date(string='付款日期', default=fields.Date.context_today, required=True)
    communication = fields.Char(string='备注')
    hide_payment_method = fields.Boolean(compute='_compute_hide_payment_method',
                                         help="Technical field used to hide the payment method if the selected journal has only one available which is 'manual'")

    @api.constrains('amount')
    def _check_amount(self):
        if not self.amount > 0.0:
            raise ValidationError('The payment amount must be strictly positive.')

    @api.depends('journal_id')
    def _compute_hide_payment_method(self):
        if not self.journal_id:
            self.hide_payment_method = True
            return
        journal_payment_methods = self.journal_id.outbound_payment_method_ids
        self.hide_payment_method = len(journal_payment_methods) == 1 and journal_payment_methods[0].code == 'manual'

    @api.onchange('journal_id')
    def _onchange_journal(self):
        if self.journal_id:
            # Set default payment method (we consider the first to be the default one)
            payment_methods = self.journal_id.outbound_payment_method_ids
            self.payment_method_id = payment_methods and payment_methods[0] or False
            # Set payment method domain (restrict to methods enabled for the journal and to selected payment type)
            return {
                'domain': {'payment_method_id': [('payment_type', '=', 'outbound'), ('id', 'in', payment_methods.ids)]}}
        return {}

    def advance_post_payment(self):
        self.ensure_one()
        context = dict(self._context or {})
        active_ids = context.get('active_ids', [])
        advance_payment = self.env['expense.advance.payment'].browse(active_ids)
        payment_type = context.get('default_payment_type')
        # Create payment and post it
        advance_payment.accounting_date = self.payment_date
        if float_compare(self.amount,advance_payment.amount-advance_payment.paid_amount,precision_digits=2)==1:
            raise UserError('付款金额不能大于单据金额')
        payment = self.env['account.payment'].create({
            'partner_type': 'supplier',
            'payment_type': payment_type,
            'res_model': 'expense.advance.payment',
            'res_id': advance_payment.id,
            'journal_id': self.journal_id.id,
            'partner_id':advance_payment.employee_id.address_home_id.id,
            'company_id': self.company_id.id,
            'payment_method_id': self.payment_method_id.id,
            'amount': self.amount,
            'currency_id': self.currency_id.id,
            'payment_date': self.payment_date,
            'communication': self.communication
        })
        payment.post()

        # 付款金额和审核金额相等 状态改为已支付
        if float_compare(advance_payment.paid_amount, advance_payment.amount, precision_digits=2) == 0:
            advance_payment.state = 'done'
        # if float_compare(advance_payment.paid_amount, advance_payment.amount,
        #                  precision_digits=2) == 0 and float_is_zero(advance_payment.advance_payment_reminding,
        #                                                             precision_digits=2):
        #     advance_payment.state = 'reconciled'
        return {'type': 'ir.actions.act_window_close'}


class expense_sheet_register_payment_wizard(models.TransientModel):
    _inherit = "hr.expense.sheet.register.payment.wizard"

    def _get_payment_vals(self):
        """ Hook for extension """
        res_id=self._context.get('active_id')
        sheet_id=self.env['hr.expense.sheet'].browse(res_id)

        if float_compare(self.amount,sheet_id.to_pay_amount,precision_digits=2)==1:
            raise UserError('付款金额不能大于单据金额')
        return {
            'partner_type': 'supplier',
            'payment_type': 'outbound',
            'res_id':res_id,
            'res_model':'hr.expense.sheet',
            'partner_id': self.partner_id.id,
            'partner_bank_account_id': self.partner_bank_account_id.id,
            'journal_id': self.journal_id.id,
            'company_id': self.company_id.id,
            'payment_method_id': self.payment_method_id.id,
            'amount': self.amount,
            'currency_id': self.currency_id.id,
            'payment_date': self.payment_date,
            'communication': self.communication
        }